package com.cyj.springioc1.datasource;


import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.util.ResourceBundle;

/**
 * @description:
 * @Author C_Y_J
 * @create 2021-02-25 11:54
 **/
public class DatasourceTest {

    /**
     * 手动创建c3p0数据源（加载jdbc.properties配置文件方式）
     */
    @Test
    public void test1() throws PropertyVetoException {
        //只需要基名
        //类加载路径下（resources目录下的文件）
        ResourceBundle jdbc = ResourceBundle.getBundle("jdbc");

        String driver = jdbc.getString("jdbc.driver");
        String url = jdbc.getString("jdbc.url");
        String username = jdbc.getString("jdbc.username");
        String password = jdbc.getString("jdbc.password");

        //创建c3p0数据源对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        System.out.println(dataSource);
        dataSource.close();
    }

    /**
     * 手动创建druid数据源（加载jdbc.properties配置文件方式）
     */
    @Test
    public void test2() throws PropertyVetoException, SQLException {
        //只需要基名
        //类加载路径下（resources目录下的文件）
        ResourceBundle jdbc = ResourceBundle.getBundle("jdbc");

        String driver = jdbc.getString("jdbc.driver");
        String url = jdbc.getString("jdbc.url");
        String username = jdbc.getString("jdbc.username");
        String password = jdbc.getString("jdbc.password");

        //创建druid数据源对象
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        System.out.println(dataSource.getConnection());
        dataSource.close();
    }


    /**
     * spring创建c3p0数据源（加载jdbc.properties配置文件方式）
     */
    @Test
    public void test3() throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        ComboPooledDataSource dataSource = (ComboPooledDataSource) applicationContext.getBean("dataSource");
        System.out.println(dataSource.getConnection());
        dataSource.close();
    }
}
